# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import json

item_list = []
book_list = []


class Scrapy03MoviePipeline:
    def open_spider(self, spider):
        self.fp = open('movie.json', 'w+', encoding='utf-8')

    def process_item(self, item, spider):
        # self.fp.write(str(item))
        item_dict = {'name': item.get('name'), 'src': item.get('src'), }
        item_list.append(item_dict)
        return item

    def close_spider(self, spider):
        self.fp.write(json.dumps(item_list, ensure_ascii=False))
        self.fp.close()


class DuShuPipeline:
    def open_spider(self, spider):
        self.fp = open('dushu.json', 'w+', encoding='utf-8')

    def process_item(self, item, spider):
        # self.fp.write(str(item))
        item_dict = {'name': item.get('name'), 'src': item.get('src'), }
        book_list.append(item_dict)
        return item

    def close_spider(self, spider):
        self.fp.write(json.dumps(book_list, ensure_ascii=False))
        self.fp.close()


from pymysql import Connection
from scrapy.utils.project import get_project_settings


class DuShuMySQLPipeline:

    def open_spider(self, spider):
        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USRE']
        self.password = settings['DB_PASSWORD']
        self.database = settings['DB_DATABASE']
        self.con = Connection(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            autocommit=True
        )
        # 获取游标对象
        self.cursor = self.con.cursor()

    def process_item(self, item, spider):
        sql = 'insert into dushu_book(name,src) values ("{}","{}")'.format(item.get('name'), item.get('src'))
        self.cursor.execute(sql)
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.con.close()
